import type { UseFetchOptions } from "#app";

type UrlType =
  | string
  | Request
  | Ref<string | Request>
  | (() => string | Request);

// 基础响应类型
export interface BaseResponse<T = any> {
  code: number;
  data: T;
  msg: string;
}

interface HttpOptions<T> extends UseFetchOptions<BaseResponse<T>> {
  showSuccess?: boolean; // 是否显示成功提示
  showError?: boolean; // 是否显示错误提示
}

export function useHttp<T = any>(url: UrlType, options: HttpOptions<T> = {}) {
  const { showSuccess = false, showError = true, ...fetchOptions } = options;
  const config = useRuntimeConfig();
  url = config.public.apiBase + url;

  const { data, error, pending, refresh } = useFetch<BaseResponse<T>>(url, {
    ...fetchOptions,
    timeout: 30000,
    onRequest: ({ options }) => {
      options.headers = new Headers(options.headers);
      options.headers.set("Authorization", "Bearer 123");
    },
    onResponse: ({ response }) => {
      if (process.client && response._data) {
        const resData = response._data as BaseResponse<T>;
        if (resData.code !== 0) {
          showError &&
            ElMessage({
              type: "error",
              message: resData.msg || "业务错误",
              duration: 3000,
            });
        } else {
          showSuccess &&
            ElMessage({
              type: "success",
              message: resData.msg || "操作成功",
              duration: 3000,
            });
        }
      }
    },
    onResponseError({ error }) {
      // 网络错误处理
      if (process.client) {
        showError &&
          ElMessage({
            type: "error",
            message: error?.message || "网络请求失败",
            duration: 5000,
          });
      }
    },
  });

  return {
    data: computed(() => data.value!.data),
    code: computed(() => data.value!.code),
    msg: computed(() => data.value!.msg),
    error,
    pending,
    refresh,
  };
}
